package com.ted.hole2.config;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.List;

import com.ted.hole2.config.HoleService.Page;
import com.ted.hole2.config.HoleService.ServiceRepository;

public class ServiceProxy implements InvocationHandler {

    private ServiceRepository<?, ?> target;

    public ServiceProxy(ServiceRepository<?, ?> target) {
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        try {
            return method.invoke(target, args);
        } catch (Exception e) {
            String namedQuery = target.getMainClass().getSimpleName() + "." + method.getName();
            if (method.getReturnType() == target.getMainClass()) {
                return target.executeOneNamedQuery(namedQuery, args, method.getParameters());
            }
            if (method.getReturnType() == List.class) {
                return target.executeListNamedQuery(namedQuery, args, method.getParameters());
            }
            if (method.getReturnType() == Page.class) {
                return target.executePageNamedQuery(namedQuery, args, method.getParameters());
            }
        }
        return null;
    }

}
